package cn.kin.controller;

import java.awt.Dialog.ModalExclusionType;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.kin.pojo.DataDictionary;
import cn.kin.pojo.Staff;
import cn.kin.service.DataDictionaryService;
import cn.kin.service.StaffService;
import cn.kin.tools.PageSupport;
import cn.kin.tools.Util;

@Controller
@RequestMapping("/staff")
public class StaffController {

	@Resource
	private StaffService staffBiz;
	
	@Resource
	private DataDictionaryService dataBiz;
	
	@RequestMapping("/login")
	public String login() {
		return "common/login";
	}
	
	@RequestMapping("/dologin")
	public String dologin(Staff staff,Model model) {
		System.out.println("dologin---------------------------------------");
		String info = loginUser(staff);
		if (!"SUCC".equals(info)) {
			model.addAttribute("failMsg", "用户不存在或密码错误！");
			return "common/login";
		} else {
			model.addAttribute("successMsg", "登陆成功！");// 返回到页面说夹带的参数

			/*return "redirect:/notice/mian";*/// 返回的页面
			return "/leader/main";
		}
	}
	
	private String loginUser(Staff user) {
		if (isRelogin(user))
			return "SUCC"; // 如果已经登陆，无需重新登录

		return shiroLogin(user); // 调用shiro的登陆验证
	}
	
	private String shiroLogin(Staff user) {
		// 组装token，包括客户公司名称、简称、客户编号、用户名称；密码
		UsernamePasswordToken token = new UsernamePasswordToken(
				user.getStaffNum(), user.getPassword().toCharArray(), null);
		token.setRememberMe(true);

		// shiro登陆验证
		try {
			SecurityUtils.getSubject().login(token);
		} catch (UnknownAccountException ex) {
			return "用户不存在或者密码错误！";
		} catch (IncorrectCredentialsException ex) {
			return "用户不存在或者密码错误！";
		} catch (AuthenticationException ex) {
			return ex.getMessage(); // 自定义报错信息
		} catch (Exception ex) {
			ex.printStackTrace();
			return "内部错误，请重试！";
		}
		return "SUCC";
	}
	
	private boolean isRelogin(Staff user) {
		Subject us = SecurityUtils.getSubject();
		if (us.isAuthenticated()) {
			return true; // 参数未改变，无需重新登录，默认为已经登录成功
		}
		return false; // 需要重新登陆
	}
	
	//注销
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		System.out.println("logout--------------------------");
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			try {
				subject.logout();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		response.sendRedirect("common/login.jsp");
	}
	
	//根据条件获取员工集合，分页信息
	@RequestMapping("/list")
	public String list(Model model,
			@RequestParam(value="staffNum",required=false)String staffNum,
			@RequestParam(value="name",required=false)String name,
			@RequestParam(value="positionID",required=false)Integer positionID,
			@RequestParam(value="pageNo",required=false)Integer pageNo,
			@RequestParam(value="dateBefore",required=false)String dateBefore,
			@RequestParam(value="dateAfter",required=false)String dateAfter) {
		Map map=new HashMap();
		map.put("staffNum",staffNum);
		map.put("name",name);
		map.put("positionID",positionID);
		if(dateBefore!=null&&!dateBefore.equals("")) {
			map.put("dateBefore",Util.strToDate(dateBefore, "yyyy-MM-dd"));
		}
		if(dateAfter!=null&&!dateAfter.equals("")) {
			map.put("dateAfter",Util.strToDate(dateAfter, "yyyy-MM-dd"));
		}
		
		PageSupport page=new PageSupport();
		page.setPageSize(4);
		page.setTotalCount(staffBiz.findCountByMap(map));
		if(pageNo==null||pageNo<1) {
			pageNo=1;
		}else if(pageNo>page.getTotalPageCount()) {
			pageNo=page.getTotalPageCount();
		}
		page.setCurrentPageNo(pageNo);
		map.put("page",page);
		
		List<Staff> sList=staffBiz.findByMap(map);
		
		List<DataDictionary> pList=dataBiz.getAllPosition();
		
		model.addAttribute("staffNum",staffNum);
		model.addAttribute("name",name);
		model.addAttribute("positionID",positionID);
		model.addAttribute("dateBefore",dateBefore);
		model.addAttribute("dateAfter",dateAfter);
		
		model.addAttribute("page",page);
		model.addAttribute("sList",sList);
		model.addAttribute("pList",pList);
		return "leader/staffList";
	}
}
